// 实现 一个异步的promise 
class PromiseA{
  state = 'pending' 
  value = null
  callBackArr = []

  constructor(exector) {
    exector(this.resolve.bind(this))
  }

  resolve(val) {
    if(this.state === 'pending') {
      if (typeof val === 'object' || typeof val === 'function') {
        let then = val.then
        if(typeof then === 'function') {
          then.call(val, this.resolve.bind(this))
        }
      }
      this.value = val
      this.state = 'resolved'
      this.callBackArr.forEach(item => this._thenCallBack(item))
    }
  }

  then(cb) {
    return new Promise(resolve => {
      this._thenCallBack({
        resolve,
        onFulfilled: cb || null
      })
    })
  }

  _thenCallBack(thenPromise) {
    const {resolve, onFulfilled} = thenPromise
    if (this.state === 'pending') return this.callBackArr.push(thenPromise)  

    if (!onFulfilled) {
      resolve(this.value)
    }

    let res = onFulfilled(this.value)
    resolve(res)

  }
}

function test() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('yellres ');
    }, 3000);
  });
}
const p1 = new PromiseA(resolve => {
  resolve('test');
})
  .then(res => {
    console.log(res);
    return test();
  })
  .then(res => {
    console.log(res);
  });